<template>
    <div>
        <label for="requiredMessage">Question：</label>
        <input id="requiredMessage" v-model="requiredMessage" placeholder="输入您的问题"/>
        <button @click="closeSse">关闭连接</button>
        <button @click="send">发送</button>
        <div id="title-message" class="white-wrap">{{ titleMessage }}</div>
        <div id="message" class="white-wrap">{{ message }}</div>
    </div>
</template>

<script>
import {fetchEventSource} from '@microsoft/fetch-event-source'

const interactionId = 15;
// const remoteUrl = 'http://121.11.118.20:7001';
const remoteUrl = 'http://localhost:8080';
let token = '';
export default {
    data() {
        return {
            source: null,
            userId: new Date().getTime(),
            requiredMessage: "",
            titleMessage: "",
            message: "",
            ctrl: null,
        };
    },
    methods: {
        async send() {
            // 先登录
            await this.login();
            // 存储 Vue 实例的引用
            const self = this;
            let requiredMessage = this.requiredMessage;
            let requestBody = {
                clientToken: new Date().getTime(),// 每次请求唯一值
                interactionId: null,// 会话ID
                question: encodeURI(requiredMessage),// 问题描述，需要URL编码
                openSearch: true,// 是否开启网络实时搜索
            };

            console.log("request token: " + token);
            this.ctrl = new AbortController();
            this.source = fetchEventSource(remoteUrl + "/treasure/conversation", {
                method: "POST",
                mode: 'cors',
                headers: {
                    "Content-Type": "application/json",
                    "token": token
                },
                body: JSON.stringify(requestBody),
                signal: this.ctrl.signal,
                onopen(event) {
                    console.log('连接成功,data=' + event.data);
                    self.titleMessage = "建立连接...\n";
                    self.titleMessage += "---会话开始---\n";
                    self.titleMessage += requiredMessage + "\n";
                },
                onmessage(event) {
                    console.log('返回数据,data=' + event.data);
                    let dataReceive = event.data;
                    let parseObject = JSON.parse(dataReceive);
                    let data = parseObject.responseMessage;
                    if (data.indexOf("SSE-END") !== -1) {
                        self.closeSse();
                        self.addMessageInnerHTML("\n");
                        self.addMessageInnerHTML("---会话完成---");
                        return;
                    }
                    self.setMessageInnerHTML(data);
                },
                onclose() {
                    // 数据返回结束时触发
                    self.closeSse();
                    console.log('关闭连接成功');
                },
                onerror(event) {
                    console.log("sse onerror:" + event);
                    self.setMessageInnerHTML("连接关闭");
                    self.closeSse();
                }
            });
        },

        closeSse() {
            this.ctrl.abort();
            const httpRequest = new XMLHttpRequest();
            httpRequest.open(
                'GET',
                remoteUrl + '/treasure/test/sse/close/' + this.userId,
                true
            );
            httpRequest.send();
            console.log("close");
        },

        setMessageInnerHTML(innerHTML) {
            this.message = innerHTML;
        },

        addMessageInnerHTML(innerHTML) {
            this.message += innerHTML + '\n';
        },

        login() {
            return new Promise((resolve, reject) => {
                const httpRequest = new XMLHttpRequest();
                httpRequest.open(
                    "POST",
                    remoteUrl + "/treasure/auth/login"
                );
                httpRequest.setRequestHeader("Content-Type", "application/json");
                httpRequest.onreadystatechange = () => {
                    if (httpRequest.readyState === 4) {
                        if (httpRequest.status === 200) {
                            token = httpRequest.getResponseHeader("token");
                            resolve(); // 登录成功，解决 Promise
                        } else {
                            reject(new Error("Login failed")); // 登录失败，拒绝 Promise
                        }
                    }
                };
                const requestBody = JSON.stringify({
                    phoneNumber: "system",
                    invitationCode: "84298",
                    password: "123456",
                    loginType: "password",
                });
                // 发送请求并包含请求体数据
                httpRequest.send(requestBody);
            });
        },
    },
};
</script>
<style>
.white-wrap {
    white-space: pre-wrap;
}

button {
    margin-left: 3px;
}
</style>
